package com.ccl.iot.dvr.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * @description：图片保存管理类
 * @author： HD
 * @time：2017/8/3
 */

public class HDImageManager {

    private static HDImageManager sInstince = null;
    public final static Bitmap.CompressFormat FORMAT_JPEG = Bitmap.CompressFormat.JPEG;
    public final static int QUALITY = 100;
    public final static String FILE_SUFFIX = ".jpg";

    public static final String PATH = Environment.getExternalStorageDirectory().getPath()
            + "/CCL2/IOT2/Images";


    public synchronized static HDImageManager getInstince() {
        if (sInstince == null) {
            sInstince = new HDImageManager();
        }
        return sInstince;
    }

    /**
     * 判断是否有图片
     *
     * @param imageID
     * @return
     */
    public boolean containsBitmap(String imageID) {
        if (imageID != null) {
            String filePath = getFilePath(getFileName(imageID));

            if (filePath != null) {
                return new File(filePath).exists();
            }
        }
        return false;
    }

    /**
     * 获取图片
     *
     * @param imageID
     * @return
     */
    public Bitmap getBitmap(String imageID) {

        if (imageID != null) {
            String fileName = getFileName(imageID);
            String filePath = getFilePath(fileName);
            if (filePath != null) {
                boolean exists = new File(filePath).exists();
                if (exists) {
                    return load(filePath);
                }
            }
        }
        return null;
    }

    public String getBitmapPath(String imageID) {
        if (imageID != null) {
            String fileName = getFileName(imageID);
            String filePath = getFilePath(fileName);
            if (filePath != null) {
                boolean exists = new File(filePath).exists();
                if (exists) {
                    return filePath;
                }
            }
        }
        return null;
    }

    /**
     * 设置图片
     *
     * @param imageID
     * @param bitmap
     * @return
     */
    public boolean setBitmap(String imageID, Bitmap bitmap) {
        if (imageID != null && bitmap != null) {
            String fileName = getFileName(imageID);
            LogUtil.i("fileName: " + fileName);
            return save(bitmap, getFilePath(fileName));
        }
        return false;
    }

    /**
     * 移除照片
     *
     * @param imageID
     * @return
     */
    public boolean removeBitmap(String imageID) {
        if (imageID != null) {
            String filePath = getFilePath(getFileName(imageID));

            if (filePath != null) {
                File file = new File(filePath);

                if (file.exists()) {
                    return file.delete();
                }
            }
        }
        return false;
    }

    private String getFilePath(String fileName) {
        if (fileName != null) {
            return PATH + File.separator + fileName;
        } else {
            return null;
        }
    }

    public boolean save(Bitmap bitmap, String filePath) {

        if (bitmap != null && filePath != null) {

            try {
                File file = new File(filePath);

                if (!file.exists()) {
                    file.getParentFile().mkdirs();
                }

                FileOutputStream out = new FileOutputStream(file);
                boolean compress = bitmap.compress(FORMAT_JPEG, QUALITY, out);
                out.flush();
                out.close();

                return compress;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }catch (IOException e) {
                e.printStackTrace();
            }
        }

        return false;
    }

    public Bitmap load(String filePath) {
        if (filePath != null) {

            Bitmap bitmap = null;

            try {

                FileInputStream fis = new FileInputStream(filePath);
                bitmap = BitmapFactory.decodeStream(fis);
                fis.close();

            } catch (Exception e) {
                e.printStackTrace();
            }

            return bitmap;
        }

        return null;
    }

    /** 过滤特殊字符
     * @param str
     * @return
     * @throws PatternSyntaxException
     */
    public static String StringFilter(String str) throws PatternSyntaxException {
        // 只允许字母和数字 // String regEx ="[^a-zA-Z0-9]";
        // 清除掉所有特殊字符
        String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("_").trim();
    }


    private String getFileName(String imageID) {
        if (imageID != null) {

            byte imageIDBytes[] = imageID.getBytes();

            if (imageIDBytes != null && imageIDBytes.length > 0) {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < imageIDBytes.length; i++) {
                    sb.append(Integer.toString(imageIDBytes[i], Character.MAX_RADIX));
                }
                return sb.toString() + FILE_SUFFIX;
            }

//           return StringFilter(imageID) + FILE_SUFFIX;
        }

        return null;
    }


}
